package com.surfilter.mq.util;

import java.io.*;

public class ByteUtils {

    /**
     * 序列化对象，该对象必须可序列化
     * @param obj
     * @return
     * @throws IOException 
     */
    public static byte[] serialize(Object obj) throws IOException {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            return baos.toByteArray();
        } catch (IOException e) {
            throw new IOException(e);
        } finally {
            if (oos != null)
                try {
                    oos.close();
                    baos.close();
                } catch (IOException e) {
                }
        }
    }
 
    /**
     * 反序列化
     * @param bits
     * @return
     * @throws IOException 
     */
    public static Object deserialize(byte[] bits) throws IOException {
        ObjectInputStream ois = null;
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bits);
            ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            throw new IOException(e);
        } finally {
            if (ois != null)
                try {
                    ois.close();
                    bais.close();
                } catch (IOException e) {
                }
        }
    }
	
}
